package com.von.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.von.entity.DictionaryGroup;
import com.von.entity.DictionaryItem;
import com.von.enums.ApiErrorCode;
import com.von.enums.CommonEnum;
import com.von.mapper.DictionaryGroupMapper;
import com.von.param.DictionaryGroupParam;
import com.von.result.R;
import com.von.service.IDictionaryGroupService;
import com.von.service.IDictionaryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 字典-组 服务实现类
 * </p>
 *
 * @author xiaosai
 * @since 2021-07-09
 */
@Service
public class DictionaryGroupServiceImpl extends ServiceImpl<DictionaryGroupMapper, DictionaryGroup> implements IDictionaryGroupService {
    @Autowired
    private IDictionaryItemService iDictionaryItemService;

    @Override
    public R<Page<DictionaryGroup>> list(DictionaryGroupParam dictionaryGroupParam) {
        Page<DictionaryGroup> page = lambdaQuery().orderByAsc(DictionaryGroup::getId).page(new Page<DictionaryGroup>(dictionaryGroupParam.getPageNum(), dictionaryGroupParam.getPageSize()));
        return R.ok(page);
    }

    @Override
    public R<String> add(DictionaryGroup dictionaryGroup) {
        if(StrUtil.isEmpty(dictionaryGroup.getName())){
            return R.failed(CommonEnum.DICTIONARYGROUP_NAME_EMPTY.getMsg());
        }
        DictionaryGroup one = lambdaQuery().eq(DictionaryGroup::getName, dictionaryGroup.getName()).one();
        if(one==null){
            save(dictionaryGroup);
            return R.ok(ApiErrorCode.OK);
        }else {
            return R.failed(CommonEnum.DICTIONARYGROUP_REPETITION.getMsg());
        }
    }

    @Override
    public R<String> update(DictionaryGroupParam dictionaryGroupParam) {
        if(dictionaryGroupParam.getId()!=null){
            DictionaryGroup dictionaryGroup = Convert.convert(DictionaryGroup.class, dictionaryGroupParam);
            dictionaryGroup.setUpdateTime(LocalDateTime.now());
            updateById(dictionaryGroup);
            return R.ok(ApiErrorCode.OK);
        }
        return R.failed(ApiErrorCode.FAILED);
    }

    @Override
    public R<String> del(Integer id) {
        if(id!=null){
            //删除字典子项
            QueryWrapper<DictionaryItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id",id);
            iDictionaryItemService.remove(queryWrapper);
            removeById(id);
            return R.ok(ApiErrorCode.OK);
        }
        return R.failed(ApiErrorCode.FAILED);
    }
}
